package weibo4android.androidexamples;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.karl.logic.AsyncBitmapLoader;
import cn.com.karl.logic.MainService;
import cn.com.karl.logic.Task;
import cn.com.karl.net.NetUtil;

import weibo4android.Paging;
import weibo4android.Status;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.androidexamples.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;

public class HomeActivity extends Activity implements IWeiboActivity,OnScrollListener {
	private ListView listView;
	// List<Status> friendsTimeline;
	private UserAdapter adapter;
	StringBuilder stringBuilder;
	private TextView textUserName;
	private Button head_new;
	private Button head_refresh;
	private ProgressDialog p;
	private int visibleLastIndex = 0;   //最后的可视项索引    
    private int visibleItemCount;       // 当前窗口可见项总数  
    private static int id=2;
    private View loadMoreView;    
    private TextView loadMoreButton;   
	private Map<Integer,View> m=new HashMap<Integer,View>();

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			textUserName.setText(msg.getData().getString("userName"));

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
				WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
		setContentView(R.layout.home);
		if (MainService.isRun == true) {

		} else {
			Intent service = new Intent(this, MainService.class);
			startService(service);
		}

		MainService.addActivity(HomeActivity.this);
		MainService.newTask(new Task(Task.HOMEREFRESH, null));

		textUserName = (TextView) findViewById(R.id.head_userName);
		head_new = (Button) this.findViewById(R.id.head_new);
		head_refresh = (Button) this.findViewById(R.id.head_refresh);
		
		 loadMoreView = getLayoutInflater().inflate(R.layout.load_more, null);    
         loadMoreButton =  (TextView) loadMoreView.findViewById(R.id.loadMoreButton);    
         loadMoreButton.setOnClickListener(new OnClickListener() {  
             
             @Override  
             public void onClick(View v) {  
                 // TODO Auto-generated method stub  
                 loadMoreButton.setText("正在加载 . . .");   //设置按钮文字loading    
                 handler.postDelayed(new Runnable() {    
                     @Override    
                     public void run() {    
                    	 List<Status> all=null;
                    	 SharedPreferences preferences = getSharedPreferences("ss",
         						Context.MODE_PRIVATE);
         				String token = preferences.getString("token", "");
         				String tokenSecret = preferences.getString("tokenSecret", "");
         				Weibo weibo = OAuthConstant.getInstance().getWeibo();
         				weibo.setToken(token, tokenSecret);
         			try {
         				System.out.println("------------------------"+token+"      "+tokenSecret);
         			//	weibo.setToken(token,tokenSecret);
         				Paging p=new Paging(id,20);
         				 all=weibo.getFriendsTimeline(p);
         				System.out.println("------------------------"+all.size());
         			} catch (WeiboException e) {
         				// TODO Auto-generated catch block
         				e.printStackTrace();
         			}  
                         for(int i=0;i<20;i++){
                        	 adapter.addItem(all.get(i));
                         }
                         adapter.notifyDataSetChanged(); //数据集变化后,通知adapter    
                         listView.setSelection(visibleLastIndex - visibleItemCount + 1); //设置选中项    
                         
                         id+=1;
                         loadMoreButton.setText("加载更多");    //恢复按钮文字    
                     }    
                 }, 100);    
             }  
         });  
         
         
		listView = (ListView) findViewById(R.id.home_list);
		
		listView.addFooterView(loadMoreView);   //设置列表底部视图    
        listView.setOnScrollListener(this);     //添加滑动监听    
        
		p = ProgressDialog.show(this, "", "正在加载，请稍候  . . .  ", true);

		head_refresh.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				/*p = ProgressDialog.show(HomeActivity.this, "",
						"正在加载，请稍候  . . .  ", true);*/
				p.show();
				MainService.newTask(new Task(Task.HOMEREFRESH, null));

			}
		});
		head_new.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(HomeActivity.this,
						NewWeiboActivity.class);
				startActivity(intent);
			}
		});
		p.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					p.dismiss();
				}
				return false;
			}
		});

		new Thread() {
			@Override
			public void run() {
				SharedPreferences preferences = getSharedPreferences("ss",
						Context.MODE_PRIVATE);
				String token = preferences.getString("token", "");
				String tokenSecret = preferences.getString("tokenSecret", "");
				Weibo weibo = OAuthConstant.getInstance().getWeibo();
				weibo.setToken(token, tokenSecret);
				String userName = preferences.getString("userName", "");

				Message msg = handler.obtainMessage();
				msg.getData().putString("userName", userName);
				handler.sendMessage(msg);

			};
		}.start();

	}

	private class UserAdapter extends BaseAdapter {
		
		private List<Status> friendsTimeline;
		private Context context;

		public UserAdapter(List<Status> friendsTimeline, Context context) {
			super();
			this.friendsTimeline = friendsTimeline;
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return friendsTimeline.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return friendsTimeline.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return friendsTimeline.get(position).getId();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			convertView=m.get(position);
			if(convertView==null){
			Status status = friendsTimeline.get(position);
		
				convertView = LayoutInflater.from(context).inflate(
						R.layout.home_item, null);
				ImageView imageIcon = (ImageView) convertView
						.findViewById(R.id.home_image);
				//异步加载图片
                new AsyncBitmapLoader().execute(imageIcon,status
						.getUser().getProfileImageURL().toString());
				/*imageIcon.setBackgroundDrawable(NetUtil.getNetImage(status
						.getUser().getProfileImageURL()));*/
				TextView textView = (TextView) convertView
						.findViewById(R.id.home_title);
				textView.setText(status.getUser().getName() + "说：");
				TextView textContent = (TextView) convertView
						.findViewById(R.id.home_content);
				textContent.setText(status.getText());
				TextView textTime = (TextView) convertView
						.findViewById(R.id.home_timeout);
				textTime.setTextSize(10);
				textTime.setText(status.getCreatedAt().toLocaleString());

				TextView home_item_swich = (TextView) convertView
						.findViewById(R.id.home_item_swich);

				if (null != status.getRetweeted_status()) {
					home_item_swich.setText(status.getRetweeted_status()
							.getText().toString());
				} else {
					LinearLayout layout = (LinearLayout) convertView
							.findViewById(R.id.home_item_layout);
					layout.setVisibility(View.GONE);
				}
			}
			m.put(position, convertView);
			return convertView;
		}
		public void addItem(Status s){
			friendsTimeline.add(s);
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub

		if (keyCode == KeyEvent.KEYCODE_BACK) {

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("你确定退出吗？")
					.setCancelable(false)
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									HomeActivity.this.finish();
									// 停止服务
									// Context.stopService();
									Intent it = new Intent(HomeActivity.this,
											MainService.class);
									HomeActivity.this.stopService(it);
									android.os.Process
											.killProcess(android.os.Process
													.myPid());
									android.os.Process
											.killProcess(android.os.Process
													.myTid());
									android.os.Process
											.killProcess(android.os.Process
													.myUid());
								}
							})
					.setNegativeButton("返回",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub

	}

	@Override
	public void refresh(Object... params) {
		// TODO Auto-generated method stub
		List<Status> all = (List<Status>) params[0];
		for (Status status : all) {
            System.out.println(status.getUser().getName() + ":" +
                               status.getText());
        }
		Log.e("Home-------------------------------", all.size() + "");
		 adapter = new UserAdapter(all, this);
		listView.setAdapter(adapter);
		p.dismiss();

	}

	//滑动时被调用 
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		 this.visibleItemCount = visibleItemCount;    
         visibleLastIndex = firstVisibleItem + visibleItemCount - 1; 
	}

	// 滑动状态改变时被调用
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub
		 int itemsLastIndex = adapter.getCount() - 1;    //数据集最后一项的索引    
         int lastIndex = itemsLastIndex + 1;             //加上底部的loadMoreView项    
         if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) {    
             //如果是自动加载,可以在这里放置异步加载数据的代码    
             Log.i("LOADMORE", "loading...");    
         }    
	}

}
